//
//  cnhbMsgAlert.m
//  HousingPoliceAssistant
//
//  Created by 云警01 on 2019/6/6.
//  Copyright © 2019 盛洋. All rights reserved.
//

#import "cnhbMsgAlert.h"

#import "MainService.h"
#import "UIColor+Addition.h"
#import <QuartzCore/QuartzCore.h>

@implementation cnhbMsgAlertButton

- (nonnull instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //        [self addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

//- (void)touchAction:(id)sender
//{
//    _actionBlock(self);
//}

- (nullable instancetype)initWithCoder:(NSCoder * __nullable)aDecoder;
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}

@end

@implementation cnhbMsgAlert

- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.rootView = [UIApplication sharedApplication].keyWindow.subviews.firstObject;
        self.top = 0;
        self.left = 0;
        self.width = 240.0;
        self.height = 170.0;
        self.msgTextColor = [UIColor whiteColor];
        self.shadowBackgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];//背景遮盖
        self.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
        self.alertAnimateType = @"FadeIn";
        self.isShowOther = false;
        self.msgTimer = [[NSTimer alloc]init];
        self.isKeyBoardShow = false;
        self.font = [UIFont systemFontOfSize:12];
        
        self.viewLabel = [[UILabel alloc]init];
        self.titleLabel = [[UILabel alloc]init];
        self.alertView = [[UIView alloc]init];
        self.alertShadowView = [[UIView alloc]init];
        self.buttons = [NSMutableArray array];
        
        if (!self.textColor) {
            self.textColor = [UIColor blackColor];
        }
        if (!self.btnTitleColor) {
            self.btnTitleColor = [UIColor colorWithHex:0x2d73b9];
        }
    }
    return self;
}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}

- (void)initData
{
}

- (void)viewDidLoad
{
    
}

- (void)showMessage:(NSString * __nullable)contentText
{
    [self showAlertType:Message title:nil contentText:contentText width:0 height:0 imageUrl:nil infoDic:nil];
}

- (void)showMessage:(NSString * __nullable)contentText withTimer:(NSTimeInterval)times
{
    self.msgTimeInterval = times;
    [self showAlertType:Message title:nil contentText:contentText width:0 height:0 imageUrl:nil infoDic:nil];
}

- (void)showAlertTitle:(NSString * __nullable)title contentText:(NSString * __nullable)contentText
{
    [self showAlertTitle:title contentText:contentText completeText:nil];
}

- (void)showAlertTitle:(NSString * __nullable)title contentText:(NSString * __nullable)contentText completeText:(NSString * __nullable)completeText
{
    [self showAlertTitle:title contentText:contentText completeText:completeText width:self.width height:self.height];
}

- (void)showAlertTitle:(NSString * __nullable)title contentText:(NSString * __nullable)contentText width:(CGFloat)width
{
    [self showAlertTitle:title contentText:contentText completeText:nil width:width height:0];
}

- (void)showAlertTitle:(NSString * __nullable)title contentText:(NSString * __nullable)contentText completeText:(NSString * __nullable)completeText width:(CGFloat)width height:(CGFloat)height
{
    [self showAlertType:Alert title:title contentText:contentText width:width height:height imageUrl:nil infoDic:nil];
    NSString *txt = completeText!=nil ? completeText : @"确定";
    [self addButton:txt target:self selector:@selector(hideView)];
}

- (void)showImageAlert:(NSString * __nullable)imageUrl
{
    [self showAlertType:ImageAlert title:nil contentText:nil width:0 height:0 imageUrl:imageUrl infoDic:nil];
}

- (void)showHtmlAlert:(NSString * __nullable)title contentText:(NSString * __nullable)contentText
{
    [self showHtmlAlert:title contentText:contentText completeText:nil];
}

- (void)showHtmlAlert:(NSString * __nullable)title contentText:(NSString * __nullable)contentText completeText:(NSString * __nullable)completeText
{
    [self showHtmlAlert:title contentText:contentText completeText:completeText width:self.width height:self.height];
}

- (void)showHtmlAlert:(NSString * __nullable)title contentText:(NSString * __nullable)contentText completeText:(NSString * __nullable)completeText width:(CGFloat)width height:(CGFloat)height
{
    [self showAlertType:HtmlAlert title:title contentText:contentText width:width height:height imageUrl:nil infoDic:nil];
    NSString *txt = completeText!=nil ? completeText : @"确定";
    [self addButton:txt target:self selector:@selector(hideView)];
}
/*!
 alert多个item
 :param: title      标题
 :param: contentText 内容
 :param: cancelTitle   取消按钮的文字
 :param: infoDic    alert宽度，标题内容item颜色配置，字典可以为nil，关键字为 width,titleColor，contentColor，itemColor
 :param: action   回调
 */
- (void)showConfirm:(NSString * __nullable)title contentText:(NSString * __nullable)contentText cancelButton:(NSString * __nullable)cancelTitle infoDic:(NSDictionary *__nullable)infoDic action:(TouchButton __nullable)action {
    if (infoDic) {
        CGFloat height = 0;
        [self showAlertType:Alert title:title contentText:contentText width:[[infoDic objectForKey:@"width"]floatValue] height:height imageUrl:nil infoDic:infoDic];
        if (cancelTitle) {
            [self addButton:cancelTitle action:action];
        }
        else {[self addButton:@"确定" action:action];}
    }
    else{
        [self showAlertType:Alert title:title contentText:contentText width:0 height:0 imageUrl:nil infoDic:nil];
        if (cancelTitle) {
            [self addButton:cancelTitle action:action];
        }
        else {
            [self addButton:@"确定" action:action];
        }
    }
}

- (CGFloat)getHeightWidth:(CGFloat)width size:(CGSize)size
{
    CGFloat radioWidth = width*1.0/size.width;
    CGFloat resultHeight = size.height*radioWidth;
    return resultHeight;
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    NSInteger btnIndex = 0;
    CGFloat y = self.alertView.frame.size.height - btnHeight;
    CGFloat btnWidth = self.alertView.frame.size.width / self.buttons.count;
    //    for (cnhbMsgAlertButton *btn in self.buttons) {
    //        btn.frame = CGRectMake(btnIndex*btnWidth, y, btnWidth, btnHeight);
    //        btnIndex ++;
    //
    //
    //    }
    for (int i = 0; i < self.buttons.count; i ++) {
        cnhbMsgAlertButton *btn = self.buttons[i];
        btn.frame = CGRectMake(btnIndex*btnWidth, y, btnWidth, btnHeight);
        btnIndex ++;
        if (i == self.buttons.count - 1) {
            UILabel *lineLabel = [[UILabel alloc]init];
            lineLabel.frame = CGRectMake(0, y, self.alertView.frame.size.width, 0.5);
            lineLabel.backgroundColor = [UIColor colorWithHex:0xCCCCCC];
            [self.alertView addSubview:lineLabel];
        }
    }
}

- (cnhbMsgAlertButton * __nullable)addButton:(NSString * __nullable)title action:(TouchButton)action
{
    cnhbMsgAlertButton *btn = [self addButtonTitle:title];
    btn.actionType = Closure;
    btn.target = self;
    btn.actionBlock = action;
    [btn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [btn addTarget:self action:@selector(buttonTapDown:) forControlEvents:UIControlEventTouchDown|UIControlEventTouchDragEnter];
    [btn addTarget:self action:@selector(buttonRelease:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside|UIControlEventTouchCancel|UIControlEventTouchDragOutside];
    
    return btn;
}

- (cnhbMsgAlertButton * __nullable)addButton:(NSString * __nullable)title target:(id __nullable)target selector:(SEL __null_unspecified)selector
{
    cnhbMsgAlertButton *btn = [self addButtonTitle:title];
    btn.actionType = Selector;
    btn.target = target;
    btn.selector = selector;
    [btn addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [btn addTarget:self action:@selector(buttonTapDown:) forControlEvents:UIControlEventTouchDown|UIControlEventTouchDragEnter];
    [btn addTarget:self action:@selector(buttonRelease:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside|UIControlEventTouchCancel|UIControlEventTouchDragOutside];
    [btn addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];//待修正
    
    return btn;
}

- (void)buttonTapped:(cnhbMsgAlertButton * __nullable)btn
{
    if (btn.actionType == Closure) {
        btn.actionBlock(btn);
        [self hideView];
    }
    else if (btn.actionType == Selector) {
        UIControl *ctrl;
        [ctrl sendAction:btn.selector to:btn.target forEvent:nil];
    }
    else{
        NSLog(@"未知返回类型");
    }
}

- (void)buttonTapDown:(cnhbMsgAlertButton * __nullable)btn
{
    CGFloat hue = 0;
    CGFloat saturation = 0;
    CGFloat brightness = 0;
    CGFloat alpha = 0;
    [btn.backgroundColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
}

- (void)buttonRelease:(cnhbMsgAlertButton * __nullable)btn
{
    NSLog(@"btn Release");
}

- (void)hideView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertWillClose:)]) {
        [self.delegate alertWillClose:self];
    }
    self.view.alpha = 1;
    [UIView animateWithDuration:0.2 animations:^{
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        if (self.delegate && [self.delegate respondsToSelector:@selector(alertDidClose:)]) {
            [self.delegate alertDidClose:self];
        }
    }];
}

- (void)hideMessage
{
    [self.msgTimer invalidate];
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertWillClose:)]) {
        [self.delegate alertWillClose:self];
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.alertView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.alertView removeFromSuperview];
        if (self.delegate && [self.delegate respondsToSelector:@selector(alertDidClose:)]) {
            [self.delegate alertDidClose:self];
        }
    }];
}
/*!
 显示alert
 :param: alertType  类型
 :param: title      标题
 :param: subContent 内容
 :param: width      宽度
 :param: height     高度
 :param: imageUrl   图片地址
 */
- (void)showAlertType:(AlertViewType)alertType title:(NSString *)title contentText:(NSString *)contentText width:(CGFloat)width height:(CGFloat)height imageUrl:(NSString *)imageUrl infoDic:(NSDictionary *)dic
{
    self.isKeyBoardShow = [MainService sharedService].IsKeyboardOpen;
    self.width = self.view.frame.size.width *0.8;
    self.alertView.tag = 1000;
    if (self.rootView == nil) {
        return;
    }
    UIView *s = [self.rootView viewWithTag:1000];
    if (s != nil) {
        //当需要快速弹出多个提示时，先将前一个提示移除
        if (self.isShowOther) {
            return;
        }
        if (alertType == Message) {
            [s removeFromSuperview];
        }else {
            return;
        }
    }
    self.titleColor = [dic objectForKey:@"titleColor"];
    self.textColor = [dic objectForKey:@"contentColor"];
    self.btnTitleColor = [dic objectForKey:@"itemColor"];
    //执行代理
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(alertWillShow:)] == true) {
        [self.delegate alertWillShow:self];
    }
    if (width > 0) {
        self.width = width;
    }
    if (height > 0) {
        self.height = height;
    }
    switch (alertType) {
        case Message:
            self.viewLabel.text = contentText;
            [self initMessage];
            [self.rootView addSubview:self.alertView];
            [self startAnimate:alertType];
            break;
        case Alert:
            self.titleLabel.text = title;
            self.viewLabel.text = contentText;
            [self initAlert];
            [self.rootView addSubview:self.view];
            [self startAnimate:alertType];
            break;
        case HtmlAlert:
            self.titleLabel.text = title;
            [self initHtmlAlert];
            [self.rootView addSubview:self.view];
            [self startAnimate:alertType];
            break;
        case ImageAlert:
            self.viewLabel.text = contentText;
            [self initImageAlert];
            [self.rootView addSubview:self.view];
            [self startAnimate:alertType];
            break;
        default:
            break;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertDidShow:)]) {
        [self.delegate alertDidShow:self];
    }
}

- (void)initMessage
{
    self.alertView.backgroundColor = self.shadowBackgroundColor;
    self.viewLabel.textColor = self.msgTextColor;
    self.viewLabel.font = AlertFont;
    self.viewLabel.textAlignment = NSTextAlignmentCenter;
    self.viewLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.viewLabel.numberOfLines = 0;
    UIFont *fontText = AlertFont;
    CGRect sz = [self.viewLabel.text boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:fontText} context:nil];
    self.viewLabel.frame = CGRectMake(self.viewLabel.frame.origin.x, self.viewLabel.frame.origin.y, sz.size.width , sz.size.height);
    self.alertView.frame = CGRectMake(self.alertView.frame.origin.x, self.alertView.frame.origin.y, sz.size.width + 20, sz.size.height + 20);
    if (self.left > 0 || self.top > 0) {
        self.alertView.frame = CGRectMake(self.left, self.top, self.alertView.frame.size.width, self.alertView.frame.size.height);
    }
    else {
        CGFloat y = (self.view.frame.size.height)/2-self.alertView.frame.size.height/2;
        if (self.isKeyBoardShow) {
            y = (self.view.frame.size.height - 216)/2-self.alertView.frame.size.height/2;
        }
        self.alertView.frame = CGRectMake(self.view.frame.size.width/2-self.alertView.frame.size.width/2, y, self.alertView.frame.size.width, self.alertView.frame.size.height);
    }
    self.viewLabel.frame = CGRectMake(self.alertView.frame.size.width/2-self.viewLabel.frame.size.width/2, self.alertView.frame.size.height/2-self.viewLabel.frame.size.height/2, self.viewLabel.frame.size.width, self.viewLabel.frame.size.height);
    [self.alertView becomeFirstResponder];
    [self.alertView addSubview:self.viewLabel];
    if (!self.msgTimeInterval) {
        self.msgTimeInterval = 2;//持续时间
    }
    self.msgTimer = [NSTimer scheduledTimerWithTimeInterval:self.msgTimeInterval target:self selector:@selector(hideMessage) userInfo:nil repeats:true];
}

- (void)initAlert
{
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = self.shadowBackgroundColor;
    self.alertShadowView.frame = self.view.frame;
    [self.view addSubview:self.alertShadowView];
    
    self.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
    if (!self.titleColor) {
        self.titleLabel.textColor = [UIColor blackColor];
    }
    else{self.titleLabel.textColor = self.titleColor;}
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    CGRect titleSz = [self.titleLabel.text boundingRectWithSize:CGSizeMake(self.width, self.height) options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14]} context:nil];
    
    if (!self.textColor) {
        self.viewLabel.textColor = [UIColor blackColor];
    }
    else {
        self.viewLabel.textColor = self.textColor;
    }
    self.viewLabel.font = self.font;
    self.viewLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    self.viewLabel.numberOfLines = 0;
    self.viewLabel.textAlignment = NSTextAlignmentCenter;
    
    CGRect contentSz = [self.viewLabel.text boundingRectWithSize:CGSizeMake(self.width - 20, self.height) options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil];
    self.titleLabel.frame = CGRectMake(0, 15, self.width + 20, titleSz.size.height+10);
    self.viewLabel.frame = CGRectMake(20, self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 5, self.width - 20, contentSz.size.height);
    self.alertView.frame = CGRectMake(self.alertView.frame.origin.x, self.alertView.frame.origin.y, self.width + 20, self.viewLabel.frame.origin.y + self.viewLabel.frame.size.height + btnHeight + 20);
    if(self.left > 0 || self.top > 0){
        self.alertView.frame = CGRectMake(self.left, self.top, self.alertView.frame.size.width, self.alertView.frame.size.height);
    } else {
        self.alertView.frame = CGRectMake(self.view.frame.size.width/2-self.alertView.frame.size.width/2, self.view.frame.size.height/2-self.alertView.frame.size.height/2, self.alertView.frame.size.width, self.alertView.frame.size.height);
    }
    
    self.alertView.backgroundColor = self.backgroundColor;
    self.alertView.layer.cornerRadius = 7;
    self.alertView.layer.masksToBounds = true;
    [self.alertView addSubview:self.titleLabel];
    [self.alertView addSubview:self.viewLabel];
    [self.alertShadowView addSubview:self.alertView];
}

- (void)initHtmlAlert
{
    /* 306-358*/
}

- (void)initImageAlert
{
    /* 361-390*/
}

- (void)startAnimate:(AlertViewType)alertType
{
    if ([self.alertAnimateType isEqualToString:@"ScrollFromUp"]) {
        if (alertType != Message) {
            self.view.alpha = 0;
        }
        self.alertView.frame = CGRectMake(self.alertView.frame.origin.x, -400, self.alertView.frame.size.width, self.alertView.frame.size.height);
        [UIView animateWithDuration:0.2 animations:^{
            if(alertType != Message) {
                self.view.alpha = 1;
                self.alertView.center = CGPointMake(self.alertView.center.x , self.rootView.center.y + 15);
            } else {
                if(self.left>0 || self.top > 0){
                    self.alertView.frame = CGRectMake(self.left, self.top + 15, self.alertView.frame.size.width, self.alertView.frame.size.height);
                } else {
                    CGFloat y = (self.view.frame.size.height)/2-self.alertView.frame.size.height/2;
                    if(self.isKeyBoardShow) {
                        y = (self.view.frame.size.height - 216)/2-self.alertView.frame.size.height/2;
                    }
                    self.alertView.frame = CGRectMake(self.view.frame.size.width/2-self.alertView.frame.size.width/2, y, self.alertView.frame.size.width, self.alertView.frame.size.height);
                }
            }
        } completion:^(BOOL finished) {
            if(alertType != Message)
            {
                [UIView animateWithDuration:0.1 animations:^{
                    self.alertView.center = self.rootView.center;
                }];
            }
            else {
                if (self.left == 0 && self.top == 0) {
                    CGFloat y = (self.view.frame.size.height)/2 - self.alertView.frame.size.height/2;
                    if (self.isKeyBoardShow) {
                        y = (self.view.frame.size.height - 216)/2-self.alertView.frame.size.height/2;
                    }
                    [UIView animateWithDuration:0.1 animations:^{
                        self.alertView.frame = CGRectMake(self.view.frame.size.width/2-self.alertView.frame.size.width/2, y, self.alertView.frame.size.width, self.alertView.frame.size.height);
                    }];
                } else {
                    [UIView animateWithDuration:0.1 animations:^{
                        self.alertView.center = self.rootView.center;
                    }];
                }
            }
        }];
    }
    if ([self.alertAnimateType isEqualToString:@"ScaleZoomIn"]) {
        if (alertType != Message) {
            self.view.alpha = 0;
        }
        self.alertView.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1);
        [UIView animateWithDuration:0.2 animations:^{
            self.alertView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1);
            if (alertType != Message) {
                self.view.alpha = 1;
            }
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                self.alertView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1);
            }];
        }];
    }
    if ([self.alertAnimateType isEqualToString:@"ScalePop"]) {
        if (alertType != Message) {
            self.view.alpha = 0;
        }
        CAKeyframeAnimation *animation;
        animation.keyPath = @"transform.scale";
        animation.values = @[@0, @(0.2*1), @(-0.2*1), @(0.2*1), @0];
        animation.keyTimes = @[@0, @0.2, @0.4, @0.6, @0.8, @1];
        animation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.5 :1.1+(1/3) :1 :1];
        animation.duration = 0.7;
        animation.additive = true;
        animation.repeatCount = 0;
        animation.beginTime = CACurrentMediaTime();//578行
    }
    if ([self.alertAnimateType isEqualToString:@"FadeIn"]) {
        if (alertType != Message) {
            self.view.alpha = 0;
        }
        self.alertView.alpha = 0;
        [UIView animateWithDuration:0.2 animations:^{
            if (alertType != Message) {
                self.view.alpha = 1;
            }
            self.alertView.alpha = 1;
        }];
    }
}

- (cnhbMsgAlertButton *)addButtonTitle:(NSString *)title
{
    cnhbMsgAlertButton *btn = [[cnhbMsgAlertButton alloc]init];
    btn.layer.masksToBounds = true;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15]];
    if (!self.btnTitleColor) {
        [btn setTitleColor:[UIColor colorWithHex:0x2d73b9] forState:UIControlStateNormal];
    }
    else{
        [btn setTitleColor:self.btnTitleColor forState:UIControlStateNormal];
    }
    btn.layer.borderColor = [UIColor colorWithHex:0xCCCCCC].CGColor;
    btn.layer.borderWidth = 0.5;
    [self.buttons addObject:btn];
    [self.alertView addSubview:btn];
    
    return btn;
}
@end
